package com.sevensoft.framework.beans.factory.xml;

import com.sevensoft.framework.beans.BeanDefinition;
import com.sevensoft.framework.beans.MutablePropertyValues;
import com.sevensoft.framework.beans.PropertyValue;
import com.sevensoft.framework.beans.factory.support.BeanDefinitionReader;
import com.sevensoft.framework.beans.factory.support.BeanDefinitionRegistry;
import com.sevensoft.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    /**
     * 声明注册表对象
     */
    private final BeanDefinitionRegistry registry;

    public XmlBeanDefinitionReader() {
        registry = new SimpleBeanDefinitionRegistry();
    }

    /**
     * 获取注册表对象
     *
     * @return
     */
    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    /**
     * 加载配置文件并在注册表中进行注册
     *
     * @param configLocation
     * @throws RuntimeException
     */
    @Override
    public void loadBeanDefinition(String configLocation) throws Exception {
        //解析xml
        SAXReader reader = new SAXReader();
        //获取类路径下的配置文件
        InputStream resourceAsStream = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        Document document = reader.read(resourceAsStream);
        Element rootElement = document.getRootElement();
        List<Element> elements = rootElement.elements();
        elements.forEach(e -> {
            //获取xml信息存储到BeanDefinition对象中
            String id = e.attributeValue("id");
            String className = e.attributeValue("class");
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);
            //读取Bean依赖的Property标签
            MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
            List<Element> propertys = e.elements("property");
            propertys.forEach(pe -> {
                String name = pe.attributeValue("name");
                String ref = pe.attributeValue("ref");
                String value = pe.attributeValue("value");
                PropertyValue propertyValue = new PropertyValue(name, ref, value);
                mutablePropertyValues.add(propertyValue);
            });
            //beanDefinition对象注册到注册表中
            beanDefinition.setMutablePropertyValues(mutablePropertyValues);
            registry.registerBeanDefinition(id,beanDefinition);
        });
    }
}
